package tq.com.tqteacher.discuss.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import tq.com.crop.CropIntent;
import tq.com.systools.system.AlertDialogHelper;
import tq.com.systools.system.FileHelper;
import tq.com.systools.system.StringHelper;
import tq.com.tqandroidim.ITQIMObserver;
import tq.com.tqandroidim.TQIM;
import tq.com.tqandroidim.TQIMMsg;
import tq.com.tqandroidim.TQIMStatus;
import tq.com.tqcom.base.BaseFragment;
import tq.com.tqcom.base.BaseTitleActivity;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.net.TQPictureUpload;
import tq.com.tqcom.util.AndroidBug5497Workaround;
import tq.com.tqcom.util.TQEventBus;
import tq.com.tqcom.util.TQLoadingHelper;
import tq.com.tqcom.util.TQSystemDefine;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.activity.captureVideo.TQCaptureActivity;
import tq.com.tqteacher.discuss.adapter.TQMsgAdapter;
import tq.com.tqteacher.model.TQCommentOverInfoModel;
import tq.com.tqteacher.model.TQLogin;
import tq.com.tqteacher.net.TQNetInterface;
import tq.com.tqteacher.view.TQViewBottomInput;
import tq.com.upload.IUploadFileListener;
import tq.com.upload.TQUploadFileManager;

public class TQDiscussMsgActivity extends BaseTitleActivity {
    private TQDiscussmsgFragment mDiscussmsgFragment = new TQDiscussmsgFragment();


    static public void show(int mId, int attId, String title, Activity pActivity){
        Intent lIntent = new Intent(pActivity, TQDiscussMsgActivity.class);
        lIntent.putExtra("AttachId", attId);
        lIntent.putExtra("meterialId", mId);
        if(!StringHelper.isEmpty(title)){
            lIntent.putExtra("title", title);
        }

        pActivity.startActivity(lIntent);
    }
    @Override
    protected BaseFragment fragment() {
        AndroidBug5497Workaround.assistActivity(this, mKeyBoradListener);
        return mDiscussmsgFragment;
    }

    @Override
    protected void initHeader(TQHeader5View pHeader5View) {
        super.initHeader(pHeader5View);
        String title = getIntent().getStringExtra("title");
        if(StringHelper.isEmpty(title)){
            title = "留言";
        }

        pHeader5View.getTitleView().setText(title);
    }

    private AndroidBug5497Workaround.IKeyBoradListener mKeyBoradListener = new AndroidBug5497Workaround.IKeyBoradListener() {
        @Override
        public void keyBoradChange(boolean show) {
            mDiscussmsgFragment.scollToBottom();
        }
    };

    static public class TQDiscussmsgFragment extends BaseFragment{
        private RecyclerView mRecyclerView;
        private TQMsgAdapter mMsgAdapter;
        private int attId = 0;
        private int meterialId = 0;

        private int page = 0;
        private SmartRefreshLayout mRefreshLayout ;

        private TQViewBottomInput mViewBottomInput;
        private Handler mHandler = new Handler(Looper.getMainLooper());
        private String mCachePicPath;

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View lView = inflater.inflate(R.layout.fragment_discuse_layout, container, false);
            mRecyclerView = lView.findViewById(R.id.recyclerView);
            if(mMsgAdapter == null){
                mMsgAdapter = new TQMsgAdapter(getContext());
            }

            LinearLayoutManager lLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
//            lLayoutManager.setReverseLayout(true);
            mRecyclerView.setAdapter(mMsgAdapter);
            mRecyclerView.setLayoutManager(lLayoutManager);
            mRecyclerView.setBackgroundColor(Color.parseColor("#eff1f3"));

            mViewBottomInput = lView.findViewById(R.id.input);
            mViewBottomInput.setISenderListener(mSenderListener);

            attId = getActivity().getIntent().getIntExtra("AttachId", 0);
            meterialId = getActivity().getIntent().getIntExtra("meterialId", 0);

            mRefreshLayout = lView.findViewById(R.id.refreshLayout);
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    page++;
                    getData();
                }
            });


            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.autoRefresh();

            return lView;
        }

        @Override
        public void onStart() {
            super.onStart();
            TQIM.getShareIm().addObserver(mITQIMObserver);
        }

        @Override
        public void onStop() {
            super.onStop();
            TQIM.getShareIm().removeObserver(mITQIMObserver);
        }

        private TQViewBottomInput.ISenderListener mSenderListener = new TQViewBottomInput.ISenderListener() {
            @Override
            public void senderText(String txt) {
                if(txt == null || txt.length() == 0) return;

                TQLoadingHelper.build(TQDiscussmsgFragment.this.getContext()).setCancelable(false).show();
                addComm(txt, TQSystemDefine.LeaveMsgType_text);
            }

            @Override
            public void senderPic() {
                ImageSelector.builder().useCamera(true)
                        .setSingle(true)
                        .start(TQDiscussmsgFragment.this, 0x01);
            }

            @Override
            public void sendCatpture() {
                TQCaptureActivity.requestCapture(null, TQDiscussmsgFragment.this, 0x02);
            }
        };


        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(resultCode != RESULT_OK || data == null) return;

            if(requestCode == 0x01) {
                ArrayList<String> files = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);

                if (files != null && files.size() > 0) {
                    String file = files.get(0);
                    gotoCrop(file);
                }

            }else if(requestCode == 0x02){
                String file = data.getStringExtra(TQCaptureActivity.RESULT_KEY);
                if(!StringHelper.isEmpty(file)){
                    uploadCapture(file);
                }
            }else if(requestCode == 0x03){
                if(FileHelper.isFileExists(mCachePicPath)){
                    uploadPic(mCachePicPath);
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        private void gotoCrop(String file){
            mCachePicPath = FileHelper.picCacheFile();

            CropIntent intent = new CropIntent();
            intent.setImagePath(file);
            intent.setRotate(false);
            intent.setOutputPath(mCachePicPath);
            startActivityForResult(intent.getIntent(this.getContext()), 0x03);
        }
        private void uploadPic(final String file){
            TQLoadingHelper.build(TQDiscussmsgFragment.this.getContext()).setCancelable(false).show();
            TQPictureUpload.uploadPicture(file, new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        TQLoadingHelper.setError(pNetResult.getErrMsg());
                        return;
                    }

                    String fileUrl = TQPictureUpload.uploadResult(pNetResult);
                    if(fileUrl == null) {
                        TQLoadingHelper.setError("上传失败，请稍后重试");
                        return;
                    }

                    addComm(fileUrl, TQSystemDefine.LeaveMsgType_image);
                }
            });
        }
        private void uploadCapture(String file){
            TQLoadingHelper.build(TQDiscussmsgFragment.this.getContext()).setCancelable(false).show();
            TQUploadFileManager.Build lBuild = new TQUploadFileManager.Build()
                    .setFile(file)
                    .setToken(TQLogin.getCurrent().getToken())
                    .setListener(new IUploadFileListener() {
                        @Override
                        public void process(long current, long total) {
                            Log.d(TAG, "process: ");
                            TQLoadingHelper.setText(String.format("进度%d%%", (int)(current/(total*1.0f) * 100)));
                        }

                        @Override
                        public void fail(String msg) {
                            Log.d(TAG, "fail: ");
                            TQLoadingHelper.setError(msg);
                        }

                        @Override
                        public void success(String filePath) {
                            Log.d(TAG, "success: ");

                            addComm(filePath, TQSystemDefine.LeaveMsgType_video);
                        }
                    });

            lBuild.start();
        }

        public void scollToBottom(){
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRecyclerView.scrollToPosition(mMsgAdapter.getItemCount() - 1);
                }
            }, 1);
        }

        private void getData(){
            TQNetInterface.getGHistoryMsg(attId, page, new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        AlertDialogHelper.show(TQDiscussmsgFragment.this.getContext(), pNetResult.getErrMsg());
                        return;
                    }

                    mRefreshLayout.finishRefresh();
                    if(pNetResult.getData() == null) return;

                    JSONArray lArray = pNetResult.getData().optJSONArray("data");
                    if(lArray == null) return;

                    ArrayList<TQCommentOverInfoModel.TQCommentInfoModel> lInfoModels = new ArrayList<>();
                    for (int i = 0; i < lArray.length(); i++){
                        try {
                            JSONObject lObject = lArray.getJSONObject(i);

                            TQCommentOverInfoModel.TQCommentInfoModel lCommentInfoModel = new TQCommentOverInfoModel.TQCommentInfoModel();
                            lCommentInfoModel.refreshMessage(lObject);

                            lInfoModels.add( lCommentInfoModel);

                        }catch (JSONException pE){
                            pE.printStackTrace();
                        }
                    }

                    mMsgAdapter.appendMore(lInfoModels);
                    if(page == 1){
                        scollToBottom();
                    }
                }
            });
            /*TQNetInterface.getAttComm(attId, page, new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        AlertDialogHelper.show(TQDiscussmsgFragment.this.getContext(), pNetResult.getErrMsg());
                        return;
                    }

                    mRefreshLayout.finishRefresh();
                    if(pNetResult.getData() == null) return;

                    JSONArray lArray = pNetResult.getData().optJSONArray("comment");
                    if(lArray == null) return;

                    ArrayList<TQCommentOverInfoModel.TQCommentInfoModel> lInfoModels = new ArrayList<>();
                    for (int i = 0; i < lArray.length(); i++){
                        try {
                            JSONObject lObject = lArray.getJSONObject(i);

                            TQCommentOverInfoModel.TQCommentInfoModel lCommentInfoModel = new TQCommentOverInfoModel.TQCommentInfoModel(lObject);
                            lInfoModels.add(0, lCommentInfoModel);

                        }catch (JSONException pE){
                            pE.printStackTrace();
                        }
                    }

                    mMsgAdapter.appendMore(lInfoModels);
                    if(page == 1){
                        scollToBottom();
                    }
                }
            });*/
        }

        private void addComm(final String content, final int type){
            /*TQNetInterface.newComm(meterialId, attId, type, content, new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        TQLoadingHelper.setError(pNetResult.getErrMsg());
                        return;
                    }

                    try {
                        if(pNetResult.getData() == null) return;

                        JSONObject lObject = pNetResult.getData().optJSONObject("comment");
                        if(lObject == null) return;

                        TQCommentOverInfoModel.TQCommentInfoModel lCommentInfoModel = new TQCommentOverInfoModel.TQCommentInfoModel();
                        lCommentInfoModel.refresh(lObject);

                        mMsgAdapter.appendNew(lCommentInfoModel);

                        scollToBottom();

                        TQEventBus.post(new TQEventBus.TQEventMessage(TQEventBus.TQEventMessage.Opertor.add, lCommentInfoModel));
                    }finally {
                        TQLoadingHelper.dimiss();
                    }
                }
            });*/

            TQIMMsg lMsg = new TQIMMsg();
            lMsg.setContentType(type);
            lMsg.setContent(content);
            lMsg.setTo(0);
            lMsg.setToGroup(attId);
            lMsg.setMsgCallback(new TQIMMsg.TQIMMsgCallback() {
                @Override
                public void result(boolean isSucess) {
                    TQLoadingHelper.dimiss();

                    if(isSucess){
                        TQCommentOverInfoModel.TQCommentInfoModel lCommentInfoModel = new TQCommentOverInfoModel.TQCommentInfoModel();
                        lCommentInfoModel.setContent(content);
                        lCommentInfoModel.setType(type);

                        mMsgAdapter.appendNew(lCommentInfoModel);

                        scollToBottom();

                        TQEventBus.post(new TQEventBus.TQEventMessage(TQEventBus.TQEventMessage.Opertor.add, lCommentInfoModel));
                    }
                }
            });

            TQIM.getShareIm().sendMessage(lMsg);
        }

        private ITQIMObserver mITQIMObserver = new ITQIMObserver() {
            @Override
            public void onStatuesChange(TQIMStatus old, TQIMStatus n) {

            }

            public long to(){
                return 0;
            }
            public long toGroup(){
                return attId;
            }
            public long from(){
                return TQLogin.getCurrent().getUserInfo().getId();
            }

            @Override
            public void onRecvMsg(JSONObject pObject) {
                if(pObject == null) return;
                TQCommentOverInfoModel.TQCommentInfoModel lCommentInfoModel = new TQCommentOverInfoModel.TQCommentInfoModel();
                lCommentInfoModel.refreshFromIm(pObject);

                if(lCommentInfoModel.getToGroup() != attId){
                    return;
                }
                mMsgAdapter.appendNew(lCommentInfoModel);

                scollToBottom();
            }
        };
    }
}
